{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <h2>学业成绩管理</h2>
        
        {% if current_user.role == 'student' %}
            <!-- 添加成绩提交卡片 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>提交学业成绩</h4>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ url_for('submit_academic') }}" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <div class="mb-3">
                            <label class="form-label">学期</label>
                            <select class="form-select" name="semester" required>
                                <option value="">请选择学期</option>
                                <option value="2023-2024">2023-2024</option>
                                <option value="2024-2025">2024-2025</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">学业成绩</label>
                            <input type="number" step="0.01" min="0" max="5" class="form-control" name="academic_score" required>
                            <div class="form-text">请输入0-4之间学年平均学分绩点成绩</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">成绩证明材料（选填）</label>
                            <input type="file" class="form-control" name="score_proof" accept=".pdf,.jpg,.jpeg,.png">
                            <div class="form-text">请上传成绩单PDF扫描件或照片（支持PDF、JPG、PNG格式，大小不超过5MB）</div>
                        </div>
                        <button type="submit" class="btn btn-primary">提交成绩</button>
                    </form>
                </div>
            </div>

            <!-- 显示历史成绩卡片 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>我的学业成绩记录</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>学业成绩</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in academic_records %}
                            <tr>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.academic_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    {% if record.status == 'pending' %}
                                        <span class="badge bg-warning">待审核</span>
                                    {% elif record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% else %}
            <!-- 教师查看界面 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>待审核成绩</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>学业成绩</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>附件</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in academic_records %}
                            {% if record.status == 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.academic_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <span class="badge bg-warning">待审核</span>
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-success" data-action="approve" data-type="academic" data-id="{{ record.id }}">通过</button>
                                    <button type="button" class="btn btn-sm btn-danger" data-action="reject" data-type="academic" data-id="{{ record.id }}">驳回</button>
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 添加已审核成绩表格 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>已审核成绩</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>学业成绩</th>
                                <th>提交时间</th>
                                <th>审核时间</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in academic_records %}
                            {% if record.status != 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>{{ record.academic_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>{{ record.update_time.strftime('%Y-%m-%d %H:%M') if record.update_time else '' }}</td>
                                <td>
                                    {% if record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% endif %}
    </div>
</div>

{{ super() }}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 为所有按钮添加点击事件监听器
    document.querySelectorAll('button[data-action]').forEach(button => {
        button.addEventListener('click', function() {
            const action = this.getAttribute('data-action');
            const type = this.getAttribute('data-type');
            const id = this.getAttribute('data-id');
            
            if (action === 'approve') {
                handleApprove(type, id);
            } else if (action === 'reject') {
                handleReject(type, id);
            }
        });
    });
});

function handleApprove(type, recordId) {
    console.log('Approving:', type, recordId);
    
    if (!confirm('确定要通过这条成绩记录吗？')) {
        return;
    }

    const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    fetch(`/approve_${type}/${recordId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': token
        },
        credentials: 'same-origin'
    })
    .then(response => {
        console.log('Response:', response);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Data:', data);
        if (data.success) {
            alert('审核通过成功！');
            window.location.reload();
        } else {
            alert('操作失败：' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}

function handleReject(type, recordId) {
    console.log('Rejecting:', type, recordId);
    
    if (!confirm('确定要驳回这条成绩记录吗？')) {
        return;
    }

    const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    fetch(`/reject_${type}/${recordId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': token
        },
        credentials: 'same-origin'
    })
    .then(response => {
        console.log('Response:', response);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Data:', data);
        if (data.success) {
            alert('驳回成功！');
            window.location.reload();
        } else {
            alert('操作失败：' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}
</script>
{% endblock %}
